package com.example.springdemo.service;

import com.example.springdemo.entity.Emp;
import com.example.springdemo.exception.BusinessException;
import com.example.springdemo.mapper.EmpMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author: Hu Shan
 * @date: 2023/3/22 20:59
 * @description: TODO
 */
@Service
@Slf4j
public class EmpServiceImpl implements EmpService {
    @Autowired
    EmpMapper empMapper;

    @Autowired
    RedisTemplate myRedisTemplate;

    public void testRedis(){
        Emp emp = empMapper.selectByPrimaryKey(2);
        myRedisTemplate.opsForValue().set("emp2", emp);
    }

    @Override
    @Cacheable(value = "emp", key = "#id", cacheManager = "redisCacheManager")
    public Emp getEmpById(int id) {
//        testRedis();
        log.info("getEmpById in service: " + id);
        Emp emp = empMapper.selectByPrimaryKey(id);
        if (emp == null){
            log.error("There is no data in mysql with id=" + id);
            throw new BusinessException("no Emp with id=" + id);
        }
        return emp;
    }

    @Override
    public void insertEmp(Emp emp) {
        empMapper.insertSelective(emp);
    }

    @Override
    public int updateEmp(Emp emp) {
        return empMapper.updateByPrimaryKeySelective(emp);
    }

    @Override
    public int deleteEmp(int id) {
        return empMapper.deleteByPrimaryKey(id);
    }
}